layui.define(['layer', 'table'], function (exports) {
    var $ = layui.jquery;
    var layer = layui.layer;
    var table = layui.table;

    var treetable = {
        // 渲染树形表格
        render: function (param) {
            param.url = param.url || '';
            param.method = param.method || 'GET';
            param.where = param.where || {};
            param.cols = param.cols || [];
            param.done = param.done || function () {};

            // 请求数据
            var that = this;
            $.ajax({
                url: param.url,
                type: param.method,
                data: param.where,
                dataType: 'json',
                success: function (res) {
                    if (res.code === 0 && res.data) {
                        // 转换数据为树形结构
                        var treeData = that.convertToTree(res.data, param.tree);
                        // 渲染表格
                        table.render({
                            elem: param.elem,
                            data: treeData,
                            cols: param.cols,
                            toolbar: param.toolbar,
                            defaultToolbar: param.defaultToolbar,
                            done: function(res) {
                                that.expandAll(param.elem.substring(1));
                                if (param.done) {
                                    param.done(res);
                                }
                            }
                        });
                    } else {
                        layer.msg(res.msg || '获取数据失败');
                    }
                },
                error: function () {
                    layer.msg('网络请求失败');
                }
            });
        },

        // 将平级数据转换为树形结构
        convertToTree: function (data, treeConfig) {
            if (!data || !treeConfig) return data;

            var idKey = treeConfig.idName || 'id';
            var pidKey = treeConfig.pidName || 'parentId';
            var childKey = 'children';

            var map = {};
            var treeData = [];

            // 建立映射关系
            data.forEach(function (item) {
                map[item[idKey]] = item;
                item[childKey] = [];
            });

            // 构建树形结构
            data.forEach(function (item) {
                var parent = map[item[pidKey]];
                if (parent) {
                    parent[childKey].push(item);
                } else {
                    treeData.push(item);
                }
            });

            return treeData;
        },

        // 展开所有节点
        expandAll: function (tableId) {
            var that = this;
            $('[data-id]').removeClass('layui-hide');
            $('.layui-icon.layui-colla-icon').removeClass('layui-icon-right').addClass('layui-icon-down');
        }
    };

    exports('treetable', treetable);
}); 